package com.sgb.kjwl.view.ui.fragment.packers;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.sgb.alimaplibrary.util.ToastUtil;
import com.sgb.kjwl.AppLazyFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityServicesCompanyBinding;
import com.sgb.kjwl.model.entity.ServicesCompanyEntity;
import com.sgb.kjwl.model.entity.packers.PickResultEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.view.ui.activity.manage.WebsiteInfoActivity;
import com.sgb.kjwl.view.ui.adapter.packers.ServicesCompanyAdapter;
import com.sgb.kjwl.view.widget.PickPopWindow1;
import com.sgb.kjwl.view.widget.ThreeLevelAreaWindow;
import com.sgb.kjwl.viewmodel.packers.ServicesCompanyModel;
import com.swgk.core.base.model.entity.SelectPopEntity;
import com.swgk.core.customview.ScreenChildTextView;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.recyclerview.entity.BaseAreaEntity;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.xrecyclerview.XRecyclerView;

import org.jetbrains.annotations.NotNull;

import java.util.List;
import java.util.Objects;

/**
 * @author : younghow
 * @date : 2021/12/6 14:38
 * description:
 */
public class LaborServiceFragment extends AppLazyFragment {

    ServicesCompanyModel viewModel;
    private ActivityServicesCompanyBinding binding;
    private ServicesCompanyAdapter servicesCompanyAdapter;

    /**
     * 企业类型
     */
    private PickPopWindow1 popType;
    private PickResultEntity pickResultType;
    /**
     * 所在区域
     */
    private ThreeLevelAreaWindow popCity;
    private PickResultEntity pickResultProvince;
    private PickResultEntity pickResultCity;
    private PickResultEntity pickResultArea;
    private String mAreaCode,mAreaName;
    private boolean isLoadMore;

    public static LaborServiceFragment newInstance(Context context) {
        return new LaborServiceFragment();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull @NotNull LayoutInflater inflater, @Nullable @org.jetbrains.annotations.Nullable ViewGroup container, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.activity_services_company,container,false);
        return binding.getRoot();
    }

    private void initFilterData(boolean isLoadMore) {
        this.isLoadMore = isLoadMore;
        viewModel.getNewList(pickResultType.getName(), pickResultProvince.getNo(), pickResultCity.getNo(), pickResultArea.getNo(), isLoadMore);
    }

    @Override
    protected void initView() {

        binding.setLifecycleOwner(this);
        viewModel = new ViewModelProvider(this).get(ServicesCompanyModel.class);

        setTextButton();
        binding.sct.onSetCallPop(new ScreenChildTextView.ICallPop() {
            @Override
            public void openPop(int position, TextView content, LinearLayout bg, SelectPopEntity entity) {
                if (position == 0) {
                    showCompanyTypePop();
                } else if (position == 1) {
                    showCityPop();
                }
            }
        });

        DividerItemDecoration divider = new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL);
        divider.setDrawable(Objects.requireNonNull(ContextCompat.getDrawable(getContext(), R.drawable.shape_list_divide)));
        binding.recyclerView.addItemDecoration(divider);
        binding.recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        binding.recyclerView.setLoadingMoreEnabled(true);
        binding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                initFilterData(false);
            }

            @Override
            public void onLoadMore() {
                initFilterData(true);
            }
        });

        if (servicesCompanyAdapter == null) {
            servicesCompanyAdapter = new ServicesCompanyAdapter(getContext(), null);
        }
        servicesCompanyAdapter.setOnItemClick(new AdapterOnItemClick<ServicesCompanyEntity>() {
            @Override
            public void onItemClick(ServicesCompanyEntity servicesCompanyEntity, int position) {
                if (TextUtils.isEmpty(servicesCompanyEntity.getId())) {
                    ToastUtil.show(getActivity(), "企业店铺id不能为空");
                    return;
                }
                WebsiteInfoActivity.start(getActivity(), servicesCompanyEntity.getNo(), WebsiteInfoActivity.WEBSITE_FOR_COMPANY);
            }
        });
        binding.recyclerView.setAdapter(servicesCompanyAdapter);

        pickResultType = new PickResultEntity();
        pickResultProvince = new PickResultEntity();
        pickResultCity = new PickResultEntity();
        pickResultArea = new PickResultEntity();

        mAreaCode = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.AREA_CODE,"");
        mAreaName = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.AREA_NAME,"");

        initLiveData();
    }

    private void initLiveData() {

        viewModel.loading.observe(getViewLifecycleOwner(), aBoolean -> DialogHelper.showProgressDialog(getContext(), null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false));

        viewModel.laborList.observe(getViewLifecycleOwner(), list -> {
            if (isLoadMore) {
                binding.recyclerView.loadMoreComplete();
                if (list != null && list.size() > 0) {
                    servicesCompanyAdapter.addDatas(list);
                }
                binding.recyclerView.setNoMore(list.size() < 10);
            } else {
                binding.recyclerView.refreshComplete();
                if (list != null && list.size() > 0) {
                    binding.emptyView.setVisibility(View.GONE);
                    servicesCompanyAdapter.setDatas(list);
                    binding.recyclerView.smoothScrollToPosition(0);
                } else {
                    servicesCompanyAdapter.clearDatas();
                    binding.emptyView.setVisibility(View.VISIBLE);
                }
            }
        });

        viewModel.typeList.observe(getViewLifecycleOwner(), pickSelectEntities -> {
            if (popType == null) {
                popType = new PickPopWindow1(getContext());
                popType.setBgView(binding.grayLayout);
                popType.setOnResultClick((PickPopWindow1.OnResultClick) (key1, key2, key3) -> {
                    pickResultType.setNo((String) key1);
                    pickResultType.setName((String) key2);
                    pickResultType.setPosition((int) key3);
                    if (TextUtils.isEmpty((String) key2) || TextUtils.equals(getString(R.string.app_all), (String) key2)) {
                        pickResultType.setName("");
                        binding.sct.contentSelect("企业类型",false,false,0);
                    } else {
                        binding.sct.contentSelect((String) key2,true,false,0);
                    }
                    initFilterData(false);
                });
                popType.setOnDismissListener(() -> binding.sct.contentSelect(!"企业类型".equals(binding.sct.getName(0)),false,0));

                popType.setData(pickSelectEntities);
            }
        });

        viewModel.cityList.observe(getViewLifecycleOwner(), new Observer<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>() {
            @Override
            public void onChanged(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> addressEntities) {
                if (popCity == null) {
                    popCity = new ThreeLevelAreaWindow(getActivity()){
                        @Override
                        protected void provinceClick(BaseAreaEntity baseAreaEntity, int position) {
                            super.provinceClick(baseAreaEntity, position);
                            pickResultProvince.setNo(baseAreaEntity.getNo());
                            pickResultProvince.setName(baseAreaEntity.getSimpleName());
                            if (getString(R.string.app_all).equals(baseAreaEntity.getSimpleName()) || pickResultProvince.getName().equals(baseAreaEntity.getSimpleName())){
                                pickResultCity.setNo("");
                                pickResultCity.setName("");
                                pickResultArea.setNo("");
                                pickResultArea.setName("");
                            }
                        }

                        @Override
                        protected void cityClick(BaseAreaEntity baseAreaEntity, int position) {
                            super.cityClick(baseAreaEntity, position);
                            pickResultCity.setNo(baseAreaEntity.getNo());
                            pickResultCity.setName(baseAreaEntity.getSimpleName());
                            if (getString(R.string.app_all).equals(baseAreaEntity.getSimpleName()) || pickResultCity.getName().equals(baseAreaEntity.getSimpleName())){
                                pickResultArea.setNo("");
                                pickResultArea.setName("");
                            }
                        }

                        @Override
                        protected void areaClick(BaseAreaEntity baseAreaEntity, int position) {
                            super.areaClick(baseAreaEntity, position);
                            pickResultArea.setNo(baseAreaEntity.getNo());
                            pickResultArea.setName(baseAreaEntity.getSimpleName());
                        }

                        @Override
                        protected void reset() {
                            super.reset();
                            pickResultProvince.clear();
                            pickResultCity.clear();
                            pickResultArea.clear();
                            binding.sct.contentSelect("全部",true,false,1);
                            popCity.dismiss();
                            initFilterData(false);
                        }
                    };
                    popCity.setBgView(binding.grayLayout);
                    popCity.setShowSimpleName(true);
                    popCity.setProvinceSingle();
                    popCity.setCitySingle();
                    popCity.setAreaSingle();
                    pickResultProvince.setName(mAreaName);
                    popCity.setOnResultClick((key1, key2, key3) -> {
                        initFilterData(false);
                        if (!getString(R.string.app_all).equals(pickResultArea.getName())&&!"".equals(pickResultArea.getName())){
                            binding.sct.contentSelect(pickResultArea.getName(),true,false,1);
                            return;
                        }else {
                            binding.sct.contentSelect(pickResultCity.getName(),true,false,1);
                        }

                        if (!getString(R.string.app_all).equals(pickResultCity.getName())&&!"".equals(pickResultCity.getName())){
                            binding.sct.contentSelect(pickResultCity.getName(),true,false,1);
                            return;
                        }else {
                            binding.sct.contentSelect(pickResultProvince.getName(),true,false,1);
                        }

                        if (!getString(R.string.app_all).equals(pickResultProvince.getName())&&!"".equals(pickResultProvince.getName())){
                            binding.sct.contentSelect(pickResultProvince.getName(),true,false,1);
                        }else {
                            binding.sct.contentSelect("全部",false,false,1);
                        }
                    });
                    popCity.setOnDismissListener(() -> binding.sct.contentSelect(!"地区".equals(binding.sct.getName(1)),false,1));

                    popCity.setDataForAll(addressEntities,true,mAreaCode);
                }
            }
        });
    }

    @Override
    protected void onLazyLoad() {
        pickResultProvince.setNo(mAreaCode);
        binding.sct.contentSelect(mAreaName,true,false,1);
        initFilterData(false);
        viewModel.getCompanyTypeModel();
        viewModel.getCityList();
    }


    /**
     * 企业类型pop
     * @param
     */
    public void showCompanyTypePop() {
        binding.sct.contentSelect(false,true,0);
        popType.showPopwindow0(binding.sct);
    }

    /**
     * 省市区pop
     * @param
     */
    public void showCityPop() {
        binding.sct.contentSelect(false,true,1);
        popCity.showPopwindow(binding.sct,0,0);
    }

    private void setTextButton(){
        SelectPopEntity selectPopEntity1 = new SelectPopEntity("企业类型", "1", false, true);
        SelectPopEntity selectPopEntity2 = new SelectPopEntity("地区", "2", false, true);
        binding.sct.addTextButton(selectPopEntity1);
        binding.sct.addTextButton(selectPopEntity2);
    }

}
